package com.lanmaoly.web.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanmaoly.web.config.DataCenter;
import com.lanmaoly.web.server.dao.TbItemCatMapper;
import com.lanmaoly.web.server.dao.TbItemMapper;
import com.lanmaoly.web.server.dao.TbTypeTemplateMapper;
import com.lanmaoly.web.server.pojo.TbItem;
import com.lanmaoly.web.server.pojo.TbItemCat;
import com.lanmaoly.web.server.pojo.TbTypeTemplate;
import com.lanmaoly.web.server.service.ItemSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ItemSearchServiceImpl implements ItemSearchService {

    @Autowired
    private TbItemCatMapper itemCatMapper;
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbTypeTemplateMapper tbTypeTemplateMapper;

    @Override
    public Map search(Map<String, Object> searchMap) {
        Map<String, Object> map = new HashMap<>(16);
        //空格处理
        String keywords = (String) searchMap.get("keywords");
        //关键字去掉空格
//        searchMap.put("keywords", keywords.replace(" ", ""));

        //1.查询列表 searchMap的条件处理完毕 下面直接用的
        map.putAll(this.searchList(searchMap));
        //2.分组查询 商品分类列表
        Set<String> categoryList = this.searchCategoryList(searchMap);
        map.put("categoryList", categoryList);

        //3.查询品牌和规格列表
        String category = (String) searchMap.get("category");
        if (StringUtils.isNotEmpty(category)) {
            map.putAll(this.searchBrandAndSpecList(category));
        } /*else {
            if (categoryList.size() > 0) {
                map.putAll(this.searchBrandAndSpecList(null));
            }
        }*/

        return map;
    }

    //查询列表
    private Map<String, Object> searchList(Map<String, Object> searchMap) {
        Map<String, Object> map = new HashMap<>(8);
        //获取页码
        Integer pageNo = (Integer) searchMap.get("pageNo");
        if (pageNo == null) {
            pageNo = 1;
        }
        //获取页大小
        Integer pageSize = (Integer) searchMap.get("pageSize");
        if (pageSize == null) {
            pageSize = 20;
        }
        String price = (String) searchMap.get("price");
        if (StringUtils.isNotEmpty(price)) {
            String[] split = price.split("-");
            searchMap.put("lowPrice", split[0]);
            String s = split[1];
            if (!"*".equals(s)) {
                searchMap.put("highPrice", s);
            }
        }
        PageHelper.startPage(pageNo, pageSize);
        Page<TbItem> page = tbItemMapper.selectBySearchVo(searchMap);
        log.info("总页数[{}}],当前页[{}}],每页条数[{}}],总记录数[{}}]",
                page.getPages(), page.getPageNum(), page.getPageSize(), page.getTotal());
        map.put("rows", page.getResult());
        //总页数
        map.put("totalPages", page.getPages());
        //总记录数
        map.put("total", page.getTotal());
        return map;
    }

    /**
     * 分组查询（查询商品分类列表）
     *
     * @return list
     */
    private Set<String> searchCategoryList(Map<String, Object> searchMap) {
        String category = (String) searchMap.get("category");
        if (StringUtils.isNotEmpty(category)) {
            Set<String> set = new HashSet<>();
            set.add(category);
            return set;
        }
        return tbItemMapper.selectCategoryBySearchMap(searchMap);
    }

    /**
     * 根据商品分类名称查询品牌和规格列表
     *
     * @param category 商品分类名称
     * @return map
     */
    private Map<String, Object> searchBrandAndSpecList(String category) {
        Map<String, Object> map = new HashMap<>(8);
        //1.根据商品分类名称得到模板ID
        Long templateId = DataCenter.getItemCat().get(category);
        if (templateId == null) {
            // 查询MySQL
            TbItemCat tbItemCat = itemCatMapper.selectByName(category);
            if (tbItemCat != null) {
                DataCenter.itemCatPut(tbItemCat.getName(), tbItemCat.getTypeId());
                templateId = tbItemCat.getTypeId();
            }
        }
        if (templateId != null) {
            //2.根据模板ID获取品牌列表
            List<Map> brandList = DataCenter.getBrandList().get(templateId);
            if (brandList == null || brandList.isEmpty()) {
                brandList = this.getBrandList(templateId);
            }
            map.put("brandList", brandList);
            log.info("品牌列表条数:[{}]", brandList.size());

            //3.根据模板ID获取规格列表
//            List<Map> specList = DataCenter.getSpecList().get(templateId);
//            map.put("specList", specList);
//            log.info("规格列表条数:[{}]", specList.size());
        }
        return map;
    }

    private List<Map> getBrandList(Long templateId) {
        TbTypeTemplate tbTypeTemplate = tbTypeTemplateMapper.selectByPrimaryKey(templateId);
        String brandIds = tbTypeTemplate.getBrandIds();
        return JSON.parseArray(brandIds, Map.class);
    }

    @Override
    public void importList(List list) {
    }

    @Override
    public void deleteByGoodsIds(List goodsIds) {
    }

}
